package com.nanhai.buddhist.college.module.collegebase.controller.admin.colleges;

import com.nanhai.buddhist.college.framework.common.pojo.CommonResult;
import com.nanhai.buddhist.college.framework.common.pojo.PageResult;
import com.nanhai.buddhist.college.framework.excel.core.util.ExcelUtils;
import com.nanhai.buddhist.college.framework.operatelog.core.annotations.OperateLog;
import com.nanhai.buddhist.college.module.collegebase.controller.admin.colleges.vo.*;
import com.nanhai.buddhist.college.module.collegebase.convert.colleges.CollegesConvert;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.colleges.CollegesDO;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.departments.DepartmentsDO;
import com.nanhai.buddhist.college.module.collegebase.service.colleges.CollegesService;
import com.nanhai.buddhist.college.module.collegebase.service.departments.DepartmentsService;
import com.nanhai.buddhist.college.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

import static com.nanhai.buddhist.college.framework.common.pojo.CommonResult.error;
import static com.nanhai.buddhist.college.framework.common.pojo.CommonResult.success;
import static com.nanhai.buddhist.college.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.nanhai.buddhist.college.module.collegebase.enums.ErrorCodeConstants.CLASSES_NOT_DELETE_XUEY;

@Api(tags = "管理后台 - 学校管理--学院")
@RestController
@RequestMapping("/collegebase/colleges")
@Validated
public class CollegesController {

    @Resource
    private CollegesService collegesService;
    @Resource
    private DepartmentsService departmentsService;



    @PostMapping("/create")
    @ApiOperation("创建学校管理--学院")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<String> createColleges(@Valid @RequestBody CollegesCreateReqVO createReqVO) {
        return success(collegesService.createColleges(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新学校管理--学院")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<Boolean> updateColleges(@Valid @RequestBody CollegesUpdateReqVO updateReqVO) {
        collegesService.updateColleges(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除学校管理--学院")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<Boolean> deleteColleges(@RequestParam("id") String id) {

        List<DepartmentsDO> departList = departmentsService.getDepartmentsListByCollegeId(id);
        if (departList != null && departList.size() > 0) {
            return error(CLASSES_NOT_DELETE_XUEY);
        }

        collegesService.deleteColleges(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得学校管理--学院")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    public CommonResult<CollegesRespVO> getColleges(@RequestParam("id") String id) {
        CollegesDO colleges = collegesService.getColleges(id);
        return success(CollegesConvert.INSTANCE.convert(colleges));
    }

    @GetMapping("/list")
    @ApiOperation("获得学校管理--学院列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    public CommonResult<List<CollegesRespVO>> getCollegesList(@RequestParam("ids") Collection<String> ids) {
        List<CollegesDO> list = collegesService.getCollegesList(ids);
        return success(CollegesConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/allList")
    @ApiOperation("获得学校管理--学院列表")
    public CommonResult<List<CollegesRespVO>> getCollegesList() {
        List<CollegesDO> list = collegesService.getCollegesAllListByPermission();
        return success(CollegesConvert.INSTANCE.convertList(list));
    }


    @GetMapping("/page")
    @ApiOperation("获得学校管理--学院分页")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    public CommonResult<PageResult<CollegesRespVO>> getCollegesPage(@Valid CollegesPageReqVO pageVO) {
        PageResult<CollegesDO> pageResult = collegesService.getCollegesPage(pageVO);

//        Set<String> strings = CollectionUtils.convertSet(pageResult.getList(), CollegesDO::getUserId);
//        Map<String, AdminUserRespDTO> longAdminUserRespDTOMap = new HashMap<>();
//        if (!strings.isEmpty()) {
//            CommonResult<List<AdminUserRespDTO>> users = adminUserApi.getUsers(strings);
//            longAdminUserRespDTOMap.putAll(CollectionUtils.convertMap(users.getData(), AdminUserRespDTO::getId));
//
//            pageResult.getList().forEach(item -> {
//                if (StringUtils.hasText(item.getUserId())) {
//                    item.setUserId(Optional.ofNullable(longAdminUserRespDTOMap).map(s -> s.get(item.getUserId())).map(AdminUserRespDTO::getNickname).orElse(""));
//                }
//            });
//        }




        return success(CollegesConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出学校管理--学院 Excel")
    @PreAuthorize("@ss.hasPermission('collegebase:college_manager')")
    @OperateLog(type = EXPORT)
    public void exportCollegesExcel(@Valid CollegesExportReqVO exportReqVO,
                                    HttpServletResponse response) throws IOException {
        List<CollegesDO> list = collegesService.getCollegesList(exportReqVO);

//        Set<String> strings = CollectionUtils.convertSet(list, CollegesDO::getUserId);
//        Map<String, AdminUserRespDTO> longAdminUserRespDTOMap = new HashMap<>();
//        if (!strings.isEmpty()) {
//            CommonResult<List<AdminUserRespDTO>> users = adminUserApi.getUsers(strings);
//            longAdminUserRespDTOMap.putAll(CollectionUtils.convertMap(users.getData(), AdminUserRespDTO::getId));
//
//            list.forEach(item -> {
//                if (StringUtils.hasText(item.getUserId())) {
//                    item.setUserId(Optional.ofNullable(longAdminUserRespDTOMap).map(s -> s.get(item.getUserId())).map(AdminUserRespDTO::getNickname).orElse(""));
//                }
//            });
//        }
        // 导出 Excel
        List<CollegesExcelVO> datas = CollegesConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "学校管理--学院.xls", "数据", CollegesExcelVO.class, datas);
    }

    @GetMapping("/getAdminUserList")
    @ApiOperation("获取系统用户 支持昵称模糊查询，不传如参数查询所有")
    public CommonResult<List<AdminUserRespDTO>> getAllAdminUserList(String findStr) {
        return success(collegesService.getAllAdminUserList(findStr));
    }

}
